﻿using PmSadis.Repositories.Abstract;
using PmSadis.Models;
using System.Linq;
using PmSadis.Dal;
using System;
using System.Data.Entity;
using System.Collections.Generic;

namespace PmSadis.Repositories
{
    /// <summary>
    /// Хранилище генконтрактов
    /// </summary>
    public class GenContractRepository : IListRepository<GenContract>
    {
        private ModelsContext _context = new ModelsContext();

        /// <summary>
        /// Полный список генконтрактов
        /// </summary>
        public IQueryable<GenContract> All
        {
            get
            {
                return _context.GenContracts;
            }
        }

        /// <summary>
        /// Удалить генконтракт
        /// </summary>
        /// <param name="id">Идентификатор генконтракта</param>
        public void Delete(object id)
        {
            var genContractId = (int)id;
            var genContract = _context.GenContracts.FirstOrDefault(x => x.ContractId == genContractId);
            if (genContract == null) return;

            _context.GenContracts.Remove(genContract);
            _context.SaveChanges();
        }

        /// <summary>
        /// Создать или редактировать генконтракт
        /// </summary>
        /// <param name="genContract">Генконтракт</param>
        public object Edit(GenContract genContract)
        {
            var dateNow = DateTime.Now;
            if (genContract.ContractId == 0)
            {
                genContract.DateCreate = dateNow;
                genContract.DateUpdate = dateNow;
                _context.Entry(genContract).State = EntityState.Added;
            }
            else
            {
                genContract.DateUpdate = dateNow;
                _context.Entry(genContract).State = EntityState.Modified;
            }

            _context.SaveChanges();

            return genContract.ContractId;
        }
    }
}
